//
//  WebAddressCollectionViewController.m
//  pushNewsManager
//
//  Created by Jobs on 8/6/17.
//  Copyright © 2017 com.Iori. All rights reserved.
//

#import "WebAddressCollectionViewController.h"
#import "Header.h"
#import "Masonry.h"
#import "LinkURLCollectionViewCell.h"
#import "GetURLListApi.h"
#import "URListEntity.h"
#import "NewsDetailViewController.h"

@implementation IndicationButton


@end

@interface WebAddressCollectionViewController ()
@property (nonatomic, copy) NSString *currentChannelID;
@property (nonatomic, strong) NSArray<URListEntity*> *dataSource;
@property (nonatomic, strong) NSMutableArray<URListEntity*> *dataArraySelected;
@property (nonatomic, strong) URLEntity *currentSelectedURLEntity;
@property (nonatomic, assign) BOOL isManagner;
@end

@implementation WebAddressCollectionViewController

-(void)initSelfProperty
{
    self.currentChannelID = @"-1";
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initSelfProperty];
    [self setUpLongPressForCollectionViewCell];
    WS(weakSelf);
    [MessageBox displayLoadingInView:weakSelf.view];
    GetURLListApi *api = [GetURLListApi new];
    api.admin_id = [UserInfo sharedUser].admin.admin_id;
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        [MessageBox removeLoading];
        if([IoriJsonHelper getErrorCode:request] == 100)
        {
            weakSelf.dataSource = [NSArray yy_modelArrayWithClass:[URListEntity class] json:[IoriJsonHelper getDictForKey:@"data" fromDict:request.responseJSONObject]];
            [weakSelf buildNaviBar];
        }
        else
        {
            [weakSelf showMessage:[IoriJsonHelper getError:request]];
        }
    } failure:^(YTKBaseRequest *request) {
        [weakSelf showMessage:[request responseString]];
        [MessageBox removeLoading];
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    NSString *result = [[UIPasteboard generalPasteboard].string lowercaseString];
    if([result hasPrefix:@"http"])
    {
        self.txtURL.text = result;
    }
}


#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    if([segue.identifier isEqualToString:@"newsDetailSegue"])
    {
        NewsDetailViewController *vc= segue.destinationViewController;
        NewsEntity *news = [NewsEntity new];
        if(sender == nil)
        {
            news.art_url = self.txtURL.text;
            
        }
        else if([sender isKindOfClass:[NSIndexPath class]])
        {
            news.art_url = self.currentSelectedURLEntity.url_list_str;
        }
        vc.news = news;
    }
}


-(UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleDefault;
}


-(void)buildNaviBar
{
    WS(weakSelf);
    self.dataArraySelected = [NSMutableArray arrayWithCapacity:4];
    NSMutableArray<URListEntity*> *dataArraySelected = self.dataArraySelected;
    URListEntity *firstEntity = [URListEntity new];
    firstEntity.channel_id = @"-1";
    firstEntity.channel_name = @"常用";
    NSMutableArray<URLEntity*> *arrayURList = [NSMutableArray arrayWithCapacity:4];
    firstEntity.list = arrayURList;
    [dataArraySelected addObject:firstEntity];
    NSString *strDocumentPath = [NSSearchPathForDirectoriesInDomains( NSLibraryDirectory, NSUserDomainMask, YES ) objectAtIndex:0];
    NSString *filePath = [strDocumentPath stringByAppendingPathComponent:@"CommonChannelURL.plist"];
    if(![[NSFileManager defaultManager] fileExistsAtPath:filePath])
    {
        NSString *file = [[NSBundle mainBundle] pathForResource:@"CommonChannelURL" ofType:@"plist"];
        NSDictionary *dictFile = [NSDictionary dictionaryWithContentsOfFile:file];
        [dictFile writeToFile:filePath atomically:YES];
    }
    NSDictionary *dictCommonChannelURL = [NSDictionary dictionaryWithContentsOfFile:filePath];
    NSArray<NSDictionary*> *urlListArray = [dictCommonChannelURL objectForKey:@"urlList"];
    [urlListArray enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        URLEntity *urlEntity = [URLEntity new];
        urlEntity.url_list_name = [obj objectForKey:@"name"];
        urlEntity.url_list_str = [obj objectForKey:@"url"];
        [arrayURList addObject:urlEntity];
    }];
    //NSDictionary *dictCommonChannelURL = []
    
    [weakSelf.dataSource enumerateObjectsUsingBlock:^(URListEntity * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop)
    {
        [dataArraySelected addObject:obj];
    }];

    NSMutableArray<IndicationButton*> *arrayCategoryItems = [NSMutableArray arrayWithCapacity:10];
    
    UIImageView *imageIndicator = nil;
    if(dataArraySelected.count > 0)
    {
        imageIndicator = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"selected"]];
        [self.categoryScrollView addSubview:imageIndicator];
        imageIndicator.frame = CGRectMake(self.categoryScrollView.frame.size.width,
                                          0,
                                          imageIndicator.frame.size.width,
                                          imageIndicator.frame.size.height);
    }
    [dataArraySelected enumerateObjectsUsingBlock:^(URListEntity * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop)
     {
         IndicationButton *itemBtn = [[IndicationButton alloc] initWithFrame:CGRectMake(0,
                                                                                            idx*2 + (idx * 40),
                                                                                            weakSelf.categoryScrollView.frame.size.width,
                                                                                            40)];
         [itemBtn setTitleColor:[UIColor darkTextColor] forState:UIControlStateNormal];
         [itemBtn addTarget:weakSelf
                     action:@selector(btnNewsCategoryItem_click:)
           forControlEvents:UIControlEventTouchUpInside];
         itemBtn.imageViewIndicator = imageIndicator;
         itemBtn.cateID = obj.channel_id;
         
         itemBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
         itemBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
         itemBtn.titleLabel.font = [UIFont systemFontOfSize:15];
         itemBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
         [itemBtn setTitle:obj.channel_name forState:UIControlStateNormal];

         [self.categoryScrollView addSubview:itemBtn];
         [arrayCategoryItems addObject:itemBtn];
         
         if(idx == 0)
         {
             dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                 [imageIndicator mas_remakeConstraints:^(MASConstraintMaker *make) {
                     make.centerY.mas_equalTo(itemBtn.mas_centerY);
                     make.leading.mas_equalTo(weakSelf.view.mas_leading);
                 }];
             });
         }
     }];
    [self.categoryScrollView setContentSize:CGSizeMake(self.categoryScrollView.frame.size.width,
                                                       40*dataArraySelected.count+ 2*dataArraySelected.count)];
    [arrayCategoryItems.firstObject sendActionsForControlEvents:UIControlEventTouchUpInside];
}

-(void)btnNewsCategoryItem_click:(IndicationButton*)btn
{
    self.currentChannelID = btn.cateID;
    self.isManagner = NO;
    [self.collectionView reloadData];
    [UIView beginAnimations:nil context:nil];
    WS(weakSelf);
    [btn.imageViewIndicator mas_remakeConstraints:^(MASConstraintMaker *make)
     {
         make.centerY.mas_equalTo(btn.mas_centerY);
         make.leading.mas_equalTo(weakSelf.categoryScrollView.mas_leading);
     }];
    [self.categoryScrollView layoutIfNeeded];
    [UIView commitAnimations];

}


- (void)setUpLongPressForCollectionViewCell
{
    UILongPressGestureRecognizer *longPressGestureRecognizer =  [[UILongPressGestureRecognizer alloc]
                                                                 initWithTarget:self
                                                                 action:@selector(longPressAction:)];
    [self.collectionView addGestureRecognizer:longPressGestureRecognizer];
}

- (void)longPressAction:(UIGestureRecognizer *)gesture
{
    NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:[gesture locationInView:self.collectionView]];
    switch (gesture.state)
    {
        case UIGestureRecognizerStateBegan:
        {
            //当长按手势刚开始时，开始执行移动操作
            //LinkURLCollectionViewCell *cell = (LinkURLCollectionViewCell*)[self.collectionView cellForItemAtIndexPath:indexPath];
            //cell.btnAction.hidden = !cell.btnAction.hidden;
            self.isManagner = YES;
            [self.collectionView reloadData];
            break;
        }
        case UIGestureRecognizerStateEnded:
        {
            break;
        }
        default:
            
            break;
    }
}

#pragma mark -collection Delegate-

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

-(NSArray<URLEntity*>*)getCurrentURLEntityList
{
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"channel_id = %@", self.currentChannelID];
    NSArray<URListEntity*> *filteredListEntity = [self.dataArraySelected filteredArrayUsingPredicate:predicate];
    return filteredListEntity.firstObject.list;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [self getCurrentURLEntityList].count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    WS(weakSelf);
    LinkURLCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    if([self.currentChannelID isEqualToString:@"-1"])
    {
        cell.isGeneralItem = NO;
        [cell.btnAction setImage:[UIImage imageNamed:@"F_away"] forState:UIControlStateNormal];
    }
    else
    {
        cell.isGeneralItem = YES;
        [cell.btnAction setImage:[UIImage imageNamed:@"F_add"] forState:UIControlStateNormal];
    }
    if(self.isManagner)
    {
        cell.btnAction.hidden = NO;
    }
    else
    {
        cell.btnAction.hidden = YES;
    }
    cell.urlEntity = [self getCurrentURLEntityList][indexPath.item];
    cell.labTitle.text = cell.urlEntity.url_list_name;
    cell.action_callback = ^(LinkURLCollectionViewCell *senderCell) {
        if(senderCell.isGeneralItem)
        {
            __block BOOL isFindSame = NO;
            NSMutableArray<URLEntity*> *array = [NSMutableArray arrayWithArray:weakSelf.dataArraySelected.firstObject.list];
            [array enumerateObjectsUsingBlock:^(URLEntity * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if([obj.url_list_name isEqualToString:senderCell.urlEntity.url_list_name]
                   && [obj.url_list_str isEqualToString:senderCell.urlEntity.url_list_str])
                {
                    isFindSame = YES;
                    *stop = YES;
                }
            }];
            if(!isFindSame)
            {
                [array addObject:senderCell.urlEntity];
            }
            weakSelf.dataArraySelected.firstObject.list = array;
            NSString *strDocumentPath = [NSSearchPathForDirectoriesInDomains( NSLibraryDirectory, NSUserDomainMask, YES ) objectAtIndex:0];
            NSString *filePath = [strDocumentPath stringByAppendingPathComponent:@"CommonChannelURL.plist"];
            NSDictionary *dictCommonChannelURL = [NSDictionary dictionaryWithContentsOfFile:filePath];
            NSMutableArray<NSMutableDictionary<NSString*, NSString*> *> *temp = [NSMutableArray arrayWithCapacity:4];
            [array enumerateObjectsUsingBlock:^(URLEntity * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop){
                NSMutableDictionary *dictValue = [NSMutableDictionary dictionary];
                [dictValue setValue:obj.url_list_name forKey:@"name"];
                [dictValue setValue:obj.url_list_str forKey:@"url"];
                [temp addObject:dictValue];
            }];
            [dictCommonChannelURL setValue:temp forKey:@"urlList"];
            [dictCommonChannelURL writeToFile:filePath atomically:YES];
            [weakSelf showMessage:@"添加成功"];
        }
        else
        {
            NSMutableArray<URLEntity*> *array = [NSMutableArray arrayWithArray:weakSelf.dataArraySelected.firstObject.list];
            [array enumerateObjectsUsingBlock:^(URLEntity * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if([obj.url_list_name isEqualToString:senderCell.urlEntity.url_list_name]
                   && [obj.url_list_str isEqualToString:senderCell.urlEntity.url_list_str])
                {
                    [array removeObject:obj];
                    *stop = YES;
                }
            }];
            weakSelf.dataArraySelected.firstObject.list = array;
            NSString *strDocumentPath = [NSSearchPathForDirectoriesInDomains( NSLibraryDirectory, NSUserDomainMask, YES ) objectAtIndex:0];
            NSString *filePath = [strDocumentPath stringByAppendingPathComponent:@"CommonChannelURL.plist"];
            NSDictionary *dictCommonChannelURL = [NSDictionary dictionaryWithContentsOfFile:filePath];
            NSMutableArray<NSMutableDictionary<NSString*, NSString*> *> *temp = [NSMutableArray arrayWithCapacity:4];
            [array enumerateObjectsUsingBlock:^(URLEntity * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop){
                NSMutableDictionary *dictValue = [NSMutableDictionary dictionary];
                [dictValue setValue:obj.url_list_name forKey:@"name"];
                [dictValue setValue:obj.url_list_str forKey:@"url"];
                [temp addObject:dictValue];
            }];
            [dictCommonChannelURL setValue:temp forKey:@"urlList"];
            [dictCommonChannelURL writeToFile:filePath atomically:YES];
            [weakSelf.collectionView reloadData];
            [weakSelf showMessage:@"删除成功"];
        }
    };
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    self.currentSelectedURLEntity = [self getCurrentURLEntityList][indexPath.item];
    [self performSegueWithIdentifier:@"newsDetailSegue" sender:indexPath];
}

#pragma mark -action-

- (IBAction)btnPasteAndGo_click:(UIButton *)sender
{
    if([[[UIPasteboard generalPasteboard].string lowercaseString] hasPrefix:@"http"])
    {
        self.txtURL.text = [UIPasteboard generalPasteboard].string;
        [self btnGo_click:nil];
    }
    else
    {
        [self showMessage:@"剪贴板中没有有效超级链接"];
    }
}

- (IBAction)btnGo_click:(UIButton *)sender
{
    if(![[self.txtURL.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] isEqualToString:@""])
    {
        [self performSegueWithIdentifier:@"newsDetailSegue" sender:nil];
    }
}

@end
